package net.sppan.blog.controller;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

import javax.annotation.Resource;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import net.sppan.blog.common.JsonResult;

@Controller
public class UploadController extends BaseController{
	
	
	@Resource
	private ServletContext servletContext;

	@ResponseBody
	@RequestMapping("/upload/image")
	public JsonResult uploadImage(@RequestParam("upload_file") MultipartFile file) throws IOException{
		return upload(file);
	}
	
	@ResponseBody
	@RequestMapping("/upload/form")
	public JsonResult uploadForm(String className,@RequestParam("upload_file") MultipartFile file) throws IOException{
		System.out.println(className);
		return upload(file);
	}
	
	@ResponseBody
	@RequestMapping("/upload/file")
	public JsonResult upload(@RequestParam("upload_file") MultipartFile file) throws IOException{
		String relativePath;
		String newFileName;
		try {
			if(!isLogin()){
				return JsonResult.create("success", false).set("msg", "没有登录不能上传文件");
			}
			if (file == null) {
				return JsonResult.create("success",false).set("msg", "上传文件为 null");
			}
			if (file.getBytes().length > 8*1024*1024) {
				return JsonResult.create("success",false).set("msg", "文件必须小于8M");
			}
			// 获取上传的文件名
			String fileName = file.getOriginalFilename();
			// 获取文件的后缀名
			String extName = fileName .substring(fileName.lastIndexOf("."));
			// 生成的文件名
			newFileName = generateFileName(getLoginUser().getId(), extName);
			// 文件保存的完整目录
			String absolutePath = servletContext.getRealPath("upload") + File.separator;
			File temp = new File(absolutePath);
			if (!temp.exists()) {
				temp.mkdirs();  // 如果目录不存在则创建
			}
			BufferedOutputStream stream = null;
			stream = new BufferedOutputStream(new FileOutputStream(absolutePath + newFileName));
			if(stream != null){
				stream.write(file.getBytes());
				stream.close();
			}
			//返回给编辑器的文件位置
			String resultFilePath = File.separator + "upload" + File.separator + newFileName;
			return JsonResult.create("success", true).set("file_path", resultFilePath);
		} catch (Exception e) {
			e.printStackTrace();
			return JsonResult.create("success",false).set("msg", e.getMessage());
		}
		
	}
	
	/**
	 * 生成规范的文件名
	 */
	private String generateFileName(Long userId, String extName) {
		return userId + "_" + System.currentTimeMillis() + extName;
	}

	@RequestMapping("show")
    public String downLoad(String filename,HttpServletResponse response){
		return downLoad(filename,"image/jpeg",response);
	}
	
	@RequestMapping("download")
    public String downLoad(String filename,String content,HttpServletResponse response){
		if(StringUtils.isEmpty(content)) {
			content = "application/force-download";
		}
		String filePath = servletContext.getRealPath("upload") + File.separator;
        File file = new File(filePath + filename);
        if(file.exists()){ //判断文件父目录是否存在
            response.setContentType(content);
            response.setHeader("Content-Disposition", "attachment;fileName=" + filename);
            
            byte[] buffer = new byte[1024];
            FileInputStream fis = null; //文件输入流
            BufferedInputStream bis = null;
            
            OutputStream os = null; //输出流
            try {
                os = response.getOutputStream();
                fis = new FileInputStream(file); 
                bis = new BufferedInputStream(fis);
                int i = bis.read(buffer);
                while(i != -1){
                    os.write(buffer);
                    i = bis.read(buffer);
                }
                
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            System.out.println("----------file download" + filename);
            try {
                bis.close();
                fis.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        return null;
    }
}
